import '../../public.dart';
import 'package:dio/dio.dart';

class ResetPasswordPage extends StatefulWidget {
  const ResetPasswordPage({super.key});

  @override
  State<ResetPasswordPage> createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends State<ResetPasswordPage> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  String? email;
  String? verificationCode;
  String? newPassword;
  String? confirmPassword;
  bool _isObscure = true;
  bool _isConfirmObscure = true;
  bool _isCountingDown = false;
  int _countdown = 60;
  Timer? _timer;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startCountdown() {
    setState(() {
      _isCountingDown = true;
      _countdown = 60;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() {
          _countdown--;
        });
      } else {
        setState(() {
          _isCountingDown = false;
        });
        timer.cancel();
      }
    });
  }

  Future<void> _getVerificationCode() async {
    if (email == null || email!.isEmpty) {
      BrnToast.show('Please enter your email address', context);
      return;
    }

    if (!RegexUtil.isEmail(email!)) {
      BrnToast.show('Please enter a valid email address', context);
      return;
    }

    try {
      await RegisterApi.getVerifyCodeForPwd(
        VerifyCodeForPwdDto(userName: email!),
      );
      if (mounted) {
        BrnToast.show('Verification code sent successfully', context);
        _startCountdown();
      }
    } catch (error) {
      if (error is DioException && mounted) {
        BrnToast.show(error.message!, context);
      }
    }
  }

  Future<void> _resetPassword() async {
    final form = formKey.currentState;
    if (form!.validate()) {
      form.save();

      try {
        await RegisterApi.resetClientUserPassword(
          ResetClientUserPasswordDto(
            userName: email!,
            verifyCode: verificationCode!,
            password: newPassword!,
          ),
        );
        if (mounted) {
          BrnToast.show('Password reset successfully', context);
          // 重置密码成功后返回登录页面
          RouterHelper.navigator.pop();
        }
      } catch (error) {
        if (error is DioException && mounted) {
          BrnToast.show(error.message!, context);
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ListView(
        children: [
          _header(),
          Form(
            key: formKey,
            child: Column(
              children: [
                _emailInput(),
                _verificationCodeInput(),
                _passwordInput(),
                _confirmPasswordInput(),
                const SizedBox(height: 40),
                _submitButton(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _header() {
    return Container(
      padding: const EdgeInsets.all(30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () => RouterHelper.navigator.pop(),
            child: Icon(
              Icons.chevron_left,
              color: Colors.grey,
              size: ScreenUtil.setSp(32).toDouble(),
            ),
          ),
          const SizedBox(height: 30),
          Text(
            'Reset Password',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 10),
          Text(
            'Please enter your email address and create a new password',
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),
          ),
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _emailInput() {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.emailAddress,
        validator: validateEmail,
        onSaved: (value) => email = value,
        onChanged: (value) => email = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Enter your email address or account name",
          labelText: "Email Address Or Account Name",
        ),
      ),
    );
  }

  Widget _verificationCodeInput() {
    return buildFormItem(
      Row(
        children: [
          Expanded(
            child: TextFormField(
              keyboardAppearance: Brightness.light,
              keyboardType: TextInputType.number,
              validator: validateVerificationCode,
              onSaved: (value) => verificationCode = value,
              cursorWidth: 1.5,
              cursorColor: const Color.fromRGBO(51, 51, 51, 1),
              decoration: getCommonInputDecoration(
                hintText: "Enter verification code",
                labelText: "Verification Code",
              ),
            ),
          ),
          const SizedBox(width: 10),
          ElevatedButton(
            onPressed: _isCountingDown ? null : _getVerificationCode,
            style: ElevatedButton.styleFrom(
              backgroundColor: _isCountingDown ? Colors.grey : Colors.black,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 15),
              minimumSize: Size.zero,
              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
            ),
            child: Text(
              _isCountingDown ? "$_countdown" : "Send Code",
              style: const TextStyle(fontSize: 12),
            ),
          ),
        ],
      ),
    );
  }

  Widget _passwordInput() {
    return buildFormItem(
      TextFormField(
        obscureText: _isObscure,
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: validatePassword,
        onSaved: (value) => newPassword = value,
        onChanged: (value) => newPassword = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Create a new password",
          labelText: "New Password",
          suffixIcon: IconButton(
            icon: Icon(
              _isObscure ? Icons.visibility : Icons.visibility_off,
              color: Colors.grey[500],
            ),
            onPressed: () {
              setState(() {
                _isObscure = !_isObscure;
              });
            },
          ),
        ),
      ),
    );
  }

  Widget _confirmPasswordInput() {
    return buildFormItem(
      TextFormField(
        obscureText: _isConfirmObscure,
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: (value) => validateConfirmPassword(value, newPassword ?? ''),
        onSaved: (value) => confirmPassword = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Confirm your new password",
          labelText: "Confirm Password",
          suffixIcon: IconButton(
            icon: Icon(
              _isConfirmObscure ? Icons.visibility : Icons.visibility_off,
              color: Colors.grey[500],
            ),
            onPressed: () {
              setState(() {
                _isConfirmObscure = !_isConfirmObscure;
              });
            },
          ),
        ),
      ),
    );
  }

  Widget _submitButton() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: TextButton(
        onPressed: _resetPassword,
        style: ButtonStyle(
          shape: WidgetStateProperty.all(
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          ),
          backgroundColor: WidgetStateProperty.all(Colors.black),
          minimumSize: WidgetStateProperty.all(const Size(double.infinity, 50)),
        ),
        child: const Text(
          'RESET PASSWORD',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}
